/*Michael Khalili
Check if it matches the username format for the site
*/
function UsernameFormatValid(strUsername) {
    return (strUsername.match(/[a-zA-Z0-9]{6,20}/) == strUsername) && (strUsername.substring(0, 1).match(/[a-zA-Z]{1}/) != null);
}
/*Michael Khalili
verify password style
*/
function PasswordFormatCorrect(strPassword) {
    return (strPassword.length >= 6 && strPassword.length <= 50);
}
/*Michael Khalili
verify password style
*/
function PasswordFormatValid(strPassword) {
    return (strPassword.length >= 6 && strPassword.length <= 50);
}
/*Michael Khalili
Return the browser brand name
*/
function BrowserBrandName() {
    //Check for IE
    if (navigator.appVersion.indexOf('MSIE') != -1) {
        var version = 0;
        temp = navigator.appVersion.split('MSIE')
        version = parseFloat(temp[1])
        if (version >= 5.5) {
            return 'IE';
        } else if (version >= 0) {
            return 'IE-OLD';
        }
    }
}
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
}

/*
Sandeep V. Tamhankar (stamhankar hotmail.com)
http://javascript.internet.com/forms/check-email.html
This script and many more are available free online at 
The JavaScript Source!! http://javascript.internet.com 
*/
function EmailFormatValid(emailStr) {
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailStr.match(emailPat);

    if (matchArray == null) {
        //alert("Email address seems incorrect (check @ and .'s)");
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    if (user.match(userPat) == null) {
        //alert("The username doesn't seem to be valid.");
        return false;
    }

    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                //alert("Destination IP address is invalid!");
                return false;
            }
        }
        return true;
    }

    var domainArray = domain.match(domainPat);
    if (domainArray == null) {
        //alert("The domain name doesn't seem to be valid.");
        return false;
    }

    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    if (domArr[domArr.length - 1].length < 2 || domArr[domArr.length - 1].length > 3) {
        //alert("The address must end in a three-letter domain, or two letter country.");
        return false;
    }

    if (len < 2) {
        //var errStr="This address is missing a hostname!";
        //alert(errStr);
        return false;
    }

    return true;
}

/*Michael Khalili
Only return filtered data of the input object being inspected
*/
function NumbersOnlyFilter(objTextbox) {
    var strValue = objTextbox.value.replace(/[^0-9.-]/g, ''); // strip non-digit chars
    if (objTextbox.value != strValue) {
        objTextbox.value = strValue;
    }
}



/* Michael Khalili
Ajax call to server and returns value
*/
// initialize XMLHttpRequest object
var xmlobj = null;

//the url, whether to use post or get and the function to get called on success
function sendRequest(strURL, blnPost, funcSuccess) {
    // check for existing requests
    if (xmlobj != null && xmlobj.readyState != 0 && xmlobj.readyState != 4) {
        xmlobj.abort();
    }
    try {
        // instantiate object for Firefox, Nestcape, etc.
        xmlobj = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // instantiate object for Internet Explorer
            xmlobj = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (e) {
            // Ajax is not supported by the browser
            xmlobj = null;
            alert('Error: Your browser does not support Ajax');
            return false;
        }
    }
    // assign state handler
    //because i'm passing a function with a function into a function i have to do it this way instead of just  = stateChecker(funcSuccess);
    xmlobj.onreadystatechange = function() { stateChecker(funcSuccess) };

    //cache bust
    if (strURL.search(/\?/) > -1) {
        strURL += '&timestamp=' + new Date().getTime();
    } else {
        strURL += '?timestamp=' + new Date().getTime();
    }

    // open socket connection
    if (blnPost) {
        var AllInputValues = FormInputValues();
        xmlobj.open('POST', strURL, true);
        xmlobj.setRequestHeader("Content-type", "application/x-www-form-UrlEncoded");
        xmlobj.setRequestHeader("Content-length", AllInputValues.length);
        xmlobj.setRequestHeader("Connection", "close");
        // send request
        xmlobj.send(AllInputValues);
    } else {
        xmlobj.open('GET', strURL, true);
        // send request
        xmlobj.send(null);
    }
}

// check request status
function stateChecker(funcSuccess) {
    // if request is completed
    var strReturn;
    if (xmlobj.readyState == 4) {
        // if status == 200 display text file
        try {
            if (xmlobj.status == 200) {
                // call function to handle return value

                // display data into container
                //AjaxReturnData=;
                strReturn = xmlobj.responseText;
            }
            else {
                strReturn = 'Ajax error 1: ' + xmlobj.statusText + '\n\n' + xmlobj.responseText;
            }
        } catch (err) {
            strReturn = 'Ajax error 2: ' + err.description;
        }
        funcSuccess(strReturn);
    }
}
function CanUseAjax() {
    if (document.getElementById && document.getElementsByTagName && document.createElement) {
        return true;
    } else {
        return false;
    }
}

/*Michael Khalili
Grabs all form input fields and values then creates a post string. 
For checkboxes it only sends the data if it's checked.
Input fields with _ are ignored because they're asp.net values and break posts to other asp.net pages.
*/
function FormInputValues() {
    var objInputFields = document.getElementsByTagName("INPUT");
    var InputData = '';
    var i;
    for (i = 0; i < objInputFields.length; i++) {
        if (objInputFields[i].id != '' && objInputFields[i].value != '' && objInputFields[i].id.substring(0, 1) != '_') {
            if (objInputFields[i].type == 'checkbox') {
                if (objInputFields[i].checked == true) { InputData += '&' + objInputFields[i].id + '=' + objInputFields[i].checked; }
            } else if (objInputFields[i].type == 'radio') {
                if (objInputFields[i].checked == true) { InputData += '&' + objInputFields[i].id + '=' + objInputFields[i].checked; }
                if (objInputFields[i].checked == true) { InputData += '&' + objInputFields[i].name + '=' + UrlEncode(objInputFields[i].value); }
            } else {
                InputData += '&' + objInputFields[i].id + '=' + UrlEncode(objInputFields[i].value);
            }
        }
    }
    objInputFields = parent.document.getElementsByTagName("select");
    for (i = 0; i < objInputFields.length; i++) {
        InputData += '&' + objInputFields[i].id + '=' + UrlEncode(objInputFields[i].value);
    }

    objInputFields = document.getElementsByTagName("TEXTAREA");
    for (i = 0; i < objInputFields.length; i++) {
        if (objInputFields[i].id != '' && objInputFields[i].id.substring(0, 1) != '_') {
            try {
                InputData += '&' + objInputFields[i].id + '=' + UrlEncode(tinyMCE.getInstanceById(objInputFields[i].id).contentDocument.body.innerHTML); //+ tinyMCE.getInstanceById(objInputFields[i].id);
            } catch (e) {
                InputData += '&' + objInputFields[i].id + '=' + UrlEncode(objInputFields[i].value);
            }
        }
    }
    objInputFields = parent.document.getElementsByTagName("select");
    for (i = 0; i < objInputFields.length; i++) {
        InputData += '&' + objInputFields[i].id + '=' + UrlEncode(objInputFields[i].value);
    }
    objInputFields = document.getElementsByTagName("iframe");
    for (i = 0; i < objInputFields.length; i++) {
        if (objInputFields[i].className == 'mceEditorIframe') {
            InputData += '&' + tinyMCE.getInstanceById(objInputFields[i].id).contentDocument.body.editorId + '=' + tinyMCE.getInstanceById(objInputFields[i].id).contentDocument.body.innerHTML;
        }
    }

    return InputData.substring(1, InputData.length); //remove the leading &
}

/*Michael Khalili
UrlEncode and decode
*/
function UrlEncode(strData) {
    strData = escape(strData);
    strData = strData.replace('+', '%2B');
    strData = strData.replace('%20', '+');
    strData = strData.replace('*', '%2A');
    strData = strData.replace('/', '%2F');
    strData = strData.replace('@', '%40');
    return strData;
}

function URLDecode(strData) {
    strData = strData.replace('+', ' ');
    strData = unescape(strData);
    return strData;
}

//Peter-Paul Koch from http://www.quirksmode.org/js/findpos.html
//no copyright http://www.quirksmode.org/about/copyright.html
function ObjectPosition(obj) {
    var curleft = 0;
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}

/*Michael Khalili
Clear form error signal 
*/
function ErrorSignalClear(obj) {
    if (typeof (obj) == 'string') {
        document.getElementById('LabelEx' + obj + 'ErrorSignal').style.visibility = 'hidden';
        //obj = document.getElementById(obj);
    } else {
        document.getElementById('LabelEx' + obj.id + 'ErrorSignal').style.visibility = 'hidden';
    }
}

/*Michael Khalili
Get Querystring value based on field name. Just like .net request.quertystring.
Returns blank string if nothing found. 

Second function does a RequestQueryString like job on an inputted string
*/
function QueryStringRequest(strFieldName) {
    return QueryStringLikeParse(window.location.search.substring(1), strFieldName);
}

function QueryStringLikeParse(strQuery, strFieldName) {
    strQuery = String(strQuery).toLowerCase();
    var aryPairs = strQuery.split("&");
    var aryPair;
    strFieldName = strFieldName.toLowerCase();

    for (i = 0; i < aryPairs.length; i++) {
        aryPair = aryPairs[i].split("=");
        if (aryPair[0] == strFieldName) {
            return aryPair[1];
        }
    }
    return '';
}
/*Michael Khalili
checks if a field is numeric and allows for floating values.
*/
function NumericValid(intValue) {
    return intValue != null && !isNaN(+intValue) && (intValue + '').replace(/\s{0,}/, '') != '';
}

/*Michael Khalili
Reads data sent back from an ajax call wrapped.
Example: <!--Start data-->the text that will be returned<!--End data-->
*/
function WrappedDataRead(strData, strStartTag, strEndTag) {
    var intStartData;
    var intEndData;
    intStartData = strData.indexOf(strStartTag);
    intEndData = strData.indexOf(strEndTag);
    if (intStartData > -1 && intEndData > -1) {
        return strData.substring((intStartData + strStartTag.length), intEndData);
    }
    return '';
}

//Michael Khalili
//Date functions
//Very basic check if the data is a date or not
function DateValid(value)
{ return (!isNaN(new Date(value).getYear()) && !isNaN(new Date(value).getMonth()) && !isNaN(new Date(value).getDay())); }

//check year passed in. value is a string and then converted to date 
function LeapYearVerify(strDate) {
    var dtDate = new Date('2/29/' + (new Date(strDate)).getFullYear());
    return dtDate.toLocaleDateString().match(/Mar/gi) == null;
}

//Find start and end of dst
function DstDetect() {
    var dtDstDetect = new Date();
    var dtDstStart = '';
    var dtDstEnd = '';
    var dtDstStartHold = ''; //Temp date hold
    var intYearDayCount = 732; //366 (include leap year) * 2 (for two years)
    var intHourOfYear = 1;
    var intDayOfYear;
    var intOffset = TimezoneDetect();

    //Start from a year ago to make sure we include any previously starting dst
    dtDstDetect = new Date()
    dtDstDetect.setUTCFullYear(dtDstDetect.getUTCFullYear() - 1);
    dtDstDetect.setUTCHours(0, 0, 0, 0);

    //Going hour by hour through the year will detect DST with shorter code but that could result in 8760 
    //FOR loops and several seconds of script execution time. Longer code narrows this down a little.
    //Go one day at a time and find out approx time of dst and if there even is DST on this computer.
    //Also need to make sure we catch the most current start and end cycle.
    for (intDayOfYear = 1; intDayOfYear <= intYearDayCount; intDayOfYear++) {
        dtDstDetect.setUTCDate(dtDstDetect.getUTCDate() + 1);

        if ((dtDstDetect.getTimezoneOffset() * (-1)) != intOffset && dtDstStartHold == '') {
            dtDstStartHold = new Date(dtDstDetect);
        }
        if ((dtDstDetect.getTimezoneOffset() * (-1)) == intOffset && dtDstStartHold != '') {
            dtDstStart = new Date(dtDstStartHold);
            dtDstEnd = new Date(dtDstDetect);
            dtDstStartHold = '';

            //DST is being used in this timezone. Narrow the time down to the exact hour the change happens
            //Remove 48 hours (a few extra to be on safe side) from the start/end date and find the exact change point
            //Go hour by hour until a change in the timezone offset is detected.
            dtDstStart.setUTCHours(dtDstStart.getUTCHours() - 48);
            dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() - 48);

            //First find when DST starts
            for (intHourOfYear = 1; intHourOfYear <= 48; intHourOfYear++) {
                dtDstStart.setUTCHours(dtDstStart.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstStart will have the correct value left in it.
                if ((dtDstStart.getTimezoneOffset() * (-1)) != intOffset) {
                    break;
                }
            }

            //Now find out when DST ends
            for (intHourOfYear = 1; intHourOfYear <= 48; intHourOfYear++) {
                dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstEnd will have the correct value left in it.
                if ((dtDstEnd.getTimezoneOffset() * (-1)) != (intOffset + 60)) {
                    break;
                }
            }

            //Check if dst is currently on for this time frame. If it is then return these values. 
            //If not then keep going. The funciton will either return the last values collected 
            //or another value that is currently in effect
            if ((new Date()).getTime() >= dtDstStart.getTime() && (new Date()).getTime() <= dtDstEnd.getTime()) {
                return new Array(dtDstStart, dtDstEnd);
            }

        }
    }
    return new Array(dtDstStart, dtDstEnd);
}

function TimezoneDetect() {
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 100; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    //go through each month to find the lowest offset to account for DST
    for (intMonth = 0; intMonth < 12; intMonth++) {
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        //To ignore daylight saving time look for the lowest offset. 
        //Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))) {
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

/*Cookie functions from Tabber control
http://www.barelyfitz.com/projects/tabber/example-cookies.html
*/
function CookieSet(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toUTCString() : "") +
        ((path) ? "; path=" + path : "; path=/") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function CookieGet(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
function CookieDelete(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*
Michael Khalili
Scroll to object
*/
function ScrollTo(objValue) {
    try {
        var objpos = ObjectPosition(objValue);
    } catch (e) { }
    try {
        scroll(0, objpos[1]);
    } catch (e) { }
    try {
        window.scrollTo(0, objpos[1]);
    } catch (e) { }
}

/*
Michael Khalili
Check if object exists
*/
function ObjectExist(objValue) {
    if (!objValue) {
        return false;
    } else {
        return true;
    }
}

/*
Michael Khalili
Ignore "Entery Key" Entry
*/
function KeyPressReturnCancelBubble(event) {
    var intKeyCode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
    if (intKeyCode == 13) {
        //event.returnValue = false;
        //event.cancel = true;
        event.cancelBubble = true;
        //return false;
    }
    return true;
}
function unescapeHTML(html) {
    var htmlNode = document.createElement("DIV");
    htmlNode.innerHTML = html;
    if (htmlNode.innerText) {
        return htmlNode.innerText;
    } else {
        return htmlNode.textContent;
    }
}

/*
Michael Khalili
Truncate text
*/
function Truncate(strText, intSize) {
    if (strText.length > intSize) {
        return strText.substr(0, intSize);
    } else {
        return strText;
    }
}

/*
Facebook share.php
*/
function fbs_click() { u = location.href; t = document.title; window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }
$j(document).ready(function() {
    $j('.jQueryOnFocusSelectAll').focus(function() {
        this.select();
    });
    $j('.jQueryOnClickSelectAll').click(function() {
        this.select();
    });

});

